package planninglanguage.conditions;

import org.jdom.Element;

import util.XMLWriter;
import base.ProxyBot;
import base.WargusGameState;
import base.WargusUnit;

public class AttackedCondition extends Condition {
	int m_unitID;
	long m_initialCycle;
	
	public AttackedCondition(int a_unitID)
	{
		m_unitID = a_unitID;
		m_initialCycle = ProxyBot.getProxyBot().getCurrCycle();
	}
	// for loading from XML
	protected AttackedCondition(int id, long cycle) {
		m_unitID = id;
		m_initialCycle = cycle;
	}
	
	public void reset()
	{
		m_initialCycle = ProxyBot.getProxyBot().getCurrCycle();
	}	
	
	public String toString(int tabs)
	{
		String n = super.toString(tabs);
		n = n + "Unit Id is: " + m_unitID;
		n = n + " initialCycle is: " + m_initialCycle;
		return n;
	}
	public boolean test(WargusGameState a_gameState)
	{
		WargusUnit u = a_gameState.getUnit(m_unitID);
//		System.out.println("AttackedCondition: test( unitID = " + m_unitID + " initialCycle = " + m_initialCycle + ")");
		
		if (u!=null) {
			System.out.println("AttackedCondition: test, the last attack was in cycle " + u.getLastAttacked());
			if (u.getLastAttacked()>=m_initialCycle) {
				return true;
			} 
		}
		return false;
	}
	
	public void writeXML(XMLWriter w) {
		w.tag("condition type=\""+this.getClass().getSimpleName()+"\"");
		{
			w.tag("unit-id", m_unitID);
			w.tag("initial-cycle", m_initialCycle); 
		}
		w.tag("/condition");
	}
	
	protected static AttackedCondition loadConditionFromXML(Element e) {
		return new AttackedCondition(Integer.parseInt(e.getChildText("unit-id")),
				Long.parseLong(e.getChildText("initial-cycle")));
	}
}
